package com.fjzn.detect.core.utils.sign;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

public class AESUtils {

    /**
     * 加密
     * @param content
     * @param secret
     * @return
     */
    public static String encryptBase64(String content,String secret){
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(),secret.getBytes(CharsetUtil.CHARSET_UTF_8)).getEncoded();
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        return  aes.encryptBase64(content);
    }

    /**
     * 解密
     * @param content
     * @param secret
     * @return
     */
    public static String decryptBase64(String content,String secret){
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(),secret.getBytes(CharsetUtil.CHARSET_UTF_8)).getEncoded();
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        return  aes.decryptStr(content);
    }

    public static String generateAESSecret(SecretLen len){
        switch (len){
            case L256:
                return RandomUtil.randomString(32);
            case L192:
                return RandomUtil.randomString(24);
        }
        return RandomUtil.randomString(16);
    }

    public static enum SecretLen{
        L128, L192,L256;
    }

    public static void main(String[] args){
        String content = "29900";
        String key = generateAESSecret(SecretLen.L128);
        System.out.println(key);
        String a = encryptBase64(content,key);
        System.out.println(a);
        //解密为字符串
        String decryptStr =decryptBase64(a, key);
        System.out.println(decryptStr);
    }
}
